import { defineStore } from 'pinia'
import { getUnreadMessageList, updateAllMessageRead } from '@/api/message'
import { getAlertData } from '@/api/alert'
import { getEquipmentIds } from '@/api/equipment'


interface IUnreadMessageItem {
  id: number
  alertMessageId: number
  alertGrade: string
  alertContent: string | null
  alertTime: string | Date
}

interface IUseMessageStore {
  totalCount: number
  unreadMessageList: Array<IUnreadMessageItem>
}

export const useMessageStore = defineStore('messageStore', {
  state: () =>
  ({
    // 未读消息数量
    totalCount: 0,
    // 未读消息列表
    unreadMessageList: []
  } as IUseMessageStore),
  actions: {
    // 获取未读消息列表
    async getUnreadMessageListAction() {
      const res = await getEquipmentIds('ALL')

      var d = new Date();
      var startTime = d.getFullYear() + "-" + (d.getMonth() + 1).toString().padStart(2, '0') + "-" + d.getDate().toString().padStart(2, '0');
      var yday = new Date();
      yday.setTime(yday.getTime() + 24 * 60 * 60 * 1000);
      var endTime = yday.getFullYear() + "-" + (yday.getMonth() + 1).toString().padStart(2, '0') + "-" + (yday.getDate().toString().padStart(2, '0'));
      let params = { equipmentIds: res.data, startTime, endTime, handleStatus: '0' }
      getAlertData(params).then(({ data }) => {


        if (data && data.length) {
          this.totalCount = data.totalCount || 0
          this.unreadMessageList = data.messages || []

        }
      })

    },

    // 更新全部消息已读
    updateAllMessageReadAction() {
      updateAllMessageRead().then(res => {
        this.totalCount = 0
        this.unreadMessageList = []
      })
    },

    // 添加未读消息列表
    addMessageAction(msg: any) {
      const index = this.unreadMessageList.findIndex(item => item.id === msg.id)


      if (index > -1) {
        this.unreadMessageList.splice(index, 1)
      } else {
        this.totalCount++
      }
      this.unreadMessageList.unshift(msg)
    },

    // 移除最新已读消息
    removeMessageAction(readId: number) {
      this.unreadMessageList.forEach((item, index) => {
        if (item.id === readId) {
          this.totalCount--
          this.unreadMessageList.splice(index, 1)
        }
      })
    }
  }
})
